#include "device.h"
#include <stdlib.h>
#include <sys/timerfd.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <unistd.h>
void device_destory(Device *dev){
    free(dev->ctx);
    free(dev);
}
int Init_timer_epoll(){
    int epoll_fd;
    struct epoll_event ev, events[MAX_EVENTS];
    int timer_fd = timerfd_create(CLOCK_MONOTONIC,TFD_NONBLOCK);
    struct itimerspec timer_spec = {
            .it_interval = {.tv_sec = 300,.tv_nsec = 0},  //5分钟间隔
            .it_value = {.tv_sec = 300,.tv_nsec = 0}      //首次触发时间
    };
    // 创建epoll实例
    if ((epoll_fd = epoll_create1(0)) < 0) {
        perror("epoll creation failed");
        close(timer_fd);
        exit(EXIT_FAILURE);
    }
    timerfd_settime(timer_fd,0,&timer_spec,NULL);
    struct epoll_event timer_ev;
    timer_ev.events = EPOLLIN;
    timer_ev.data.fd = timer_fd; // 使用fd字段区分定时器
    if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, timer_fd, &timer_ev) == -1) {
        perror("epoll_ctl");
        close(timer_fd);
        close(epoll_fd);
        return -1;
    }

    //未完成
    return 0;
}

DeviceNode* init_device_list() {
    return NULL;
}
DeviceNode* insert_device(DeviceNode *head, Device *device,int collect_time_interval) {
    DeviceNode *new_node = (DeviceNode *)malloc(sizeof(DeviceNode));
    if (!new_node) {
        perror("malloc failed");
        return head;
    }
    struct itimerspec timer_spec = {
            .it_interval = {.tv_sec = 300,.tv_nsec = 0},  //5分钟间隔
            .it_value = {.tv_sec = 300,.tv_nsec = 0}      //首次触发时间
    };
    device->ctx->collect_interval_time = timer_spec;
    new_node->device = device;
    new_node->next = head;
    return new_node;
}

DeviceNode* delete_device(DeviceNode *head, int sock_fd) {
    DeviceNode *curr = head;
    DeviceNode *prev = NULL;

    while (curr) {
        if (curr->device->ctx->sock_fd == sock_fd) {
            if (prev) {
                prev->next = curr->next;
            } else {
                head = curr->next;
            }
            free(curr->device);
            free(curr);
            return head;
        }
        prev = curr;
        curr = curr->next;
    }
    return head;
}
Device* find_device(DeviceNode *head, int sock_fd) {
    while (head) {
        if (head->device->ctx->sock_fd == sock_fd) {
            return head->device;
        }
        head = head->next;
    }
    return NULL;
}
int modify_device(DeviceNode *head, int sock_fd, DeviceState new_state, int new_a) {
    Device *device = find_device(head, sock_fd);
    if (!device) return -1;

    device->ctx->state = new_state;
    device->data.a = new_a;
    return 0;
}
void free_device_list(DeviceNode *head) {
    while (head) {
        DeviceNode *tmp = head;
        head = head->next;
        free(tmp->device);
        free(tmp);
    }
}

